package genedit.controller.interfaceActions;

import genedit.gui.GFileChooser;
import genedit.gui.GMainFrame;
import genedit.gui.GProjectTree;
import genedit.model.Project;
import genedit.model.Workspace;
import genedit.model.graph.GraphDocument;
import genedit.utility.CodeGenerator;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.tree.TreeNode;

public class GGenerateCodeA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	protected static GGenerateCodeA instance = null;

	protected GGenerateCodeA() {
		putValue(NAME, "Generate code");
		putValue(SHORT_DESCRIPTION, "Generate code");
		//putValue(SMALL_ICON, new ImageIcon("resources/icons/close.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_G);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_G, KeyEvent.CTRL_MASK));
	}

	public static AbstractAction getInstance() {
		if (instance == null)
			instance = new GGenerateCodeA();
		return instance;
	}

	/**
	 * Akcija gasi aplikaciju.
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		//pronadji aktivni projekat
		GraphDocument document = null;
		TreeNode element = null;
		element = (TreeNode) GProjectTree.getInstance().getTree()
				.getLastSelectedPathComponent();
		if (element!=null) {
			if (element instanceof GraphDocument) {
				GMainFrame.getInstance().documentSaved(document);
				document = (GraphDocument) element;
			}
		} else if (Workspace.getInstance().getActiveDocument() != null) {
			document = Workspace.getInstance().getActiveDocument().getModel();
			GMainFrame.getInstance().documentSaved(document);
			element = (TreeNode) document;
		} else {
			return;
		}

		while (!(element instanceof Project)){
			if(element instanceof Workspace)
				return;
			element = element.getParent();
		}

		Project project=(Project)element;
		
		//izaberi lokaciju za generisanje koda i generisi kod
		GFileChooser.getInstance(true).setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		GFileChooser.getInstance(true).setDialogType(JFileChooser.OPEN_DIALOG);
		if (GFileChooser.getInstance(true).showSaveDialog(GMainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) {
			File selectedDirectory =new File(GFileChooser.getInstance(true).getSelectedFile().toString());
			if(selectedDirectory.exists()&&selectedDirectory.isDirectory()){
				CodeGenerator.generateCode(project, selectedDirectory);
			}
		}
		GFileChooser.getInstance(true).setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		File workspacePath=Workspace.getInstance().getPath();
		GFileChooser.getInstance(false).setCurrentDirectory(workspacePath);
	}

}